package info.itloser.learnkotlindemo.adapter

import android.content.Context
import android.media.Image
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import info.itloser.learnkotlindemo.R
import info.itloser.learnkotlindemo.bean.Fruit

/**
 * 说明： 自定义ArrayAdapter
 * 作者： itloser.info
 * 日期： 2022/3/29 14:21
 * 备注：
 */
class FruitListAdapter(context: Context, private val layoutId: Int, private val fruits: List<Fruit>) :
    ArrayAdapter<Fruit>(context, layoutId, fruits) {

    /**
     * ViewHolder
     */
    inner class FruitHolder(val ivRes: ImageView, val tvName: TextView)

    /**
     * 重写这个方法
     */
    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

        val view: View

        val fruitHolder: FruitHolder

        if (convertView == null) {

            view = LayoutInflater.from(context).inflate(layoutId, parent, false)

            fruitHolder = FruitHolder(
                view.findViewById(R.id.iv_res),
                view.findViewById(R.id.tv_name)
            )

            view.tag = fruitHolder

        } else {

            view = convertView
            fruitHolder = view.tag as FruitHolder

        }

        //获取当前项的水果
        val fruit = fruits[position]

        //设置图片资源
        fruitHolder.ivRes.setImageResource(fruit.resId)

        //设置文字
        fruitHolder.tvName.text = fruit.name

        return view
    }

}